package com.atguigu.flink.chapter11;

import com.atguigu.flink.chapter05.Source.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/1/27 14:19
 */
public class Flink10_TimeAttr_EventTime {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .fromElements(
                        new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((element, ts) -> element.getTs())
                );

        // 1.创建 表的 执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // TODO 方式一:在 流 转换成 表的时候，指定 事件时间(注意，流 一定要指定 事件时间的提取 和 watermark的生成)
        // 1）在 额外字段 指定事件时间 ： 不会改变数据本身的格式，额外字段就是一个年月日类型的数据
//        Table inputTable = tableEnv.fromDataStream(sensorDS, $("id"), $("ts"), $("vc"), $("et").rowtime());
        // 2）从 已有字段 指定 事件时间： 会改变指定的已有字段的类型，变成年月日
//        Table inputTable = tableEnv.fromDataStream(sensorDS, $("id"), $("ts").rowtime(), $("vc"));

//        inputTable.execute().print();


        // TODO 方式二：在 使用 SQL 创建表 的时候指定
        // 事件时间字段，必须是 timestamp(3) 类型：yyyy-MM-ddTHH:mm:ss.毫秒
        //  毫秒级的时间戳： 先用from_unixtime转成年月日，再用to_timestamp 转成 timestamp(3)类型
        tableEnv.executeSql("create table sensor(" +
                "id string," +
                "ts bigint," +
                "vc int, " +
                "t as to_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'))," +
                "watermark for t as t - interval '5' second)" +
                "with("
                + "'connector' = 'filesystem',"
                + "'path' = 'input/sensor-sql.txt',"
                + "'format' = 'csv'"
                + ")"
        );

        tableEnv.executeSql("select * from sensor").print();


    }
}
